﻿using System;
using System.Collections.Generic;
using System.Reflection;
using EasyCommonCore.Extension.CustomerAttribute;

namespace EasyCommonCore.Common
{
    /// <summary>
    /// 枚举帮助类
    /// </summary>
    public static class EnumCommon
    {
        #region 获取列特性
        /// <summary>
        /// 获取列特性
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        private static EnumAttribute GetTableColumnAttribute<T>(string propertyName)
        {
            EnumAttribute m = null;
            Type t = typeof(T);
            PropertyInfo[] arryProperty = t.GetProperties();
            if (arryProperty != null)
            {
                foreach (PropertyInfo p in arryProperty)
                {
                    if (p.Name == propertyName)
                    {
                        m = p.GetCustomAttribute<EnumAttribute>();
                    }
                }
            }

            return m;
        }
        #endregion

        #region 返回枚举项的描述信息
        /// <summary>
        /// 返回枚举项的描述信息。
        /// </summary>
        /// <param name="value">要获取描述信息的枚举项。</param>
        /// <returns>枚举想的描述信息。</returns>
        public static string GetDescription<T>(this System.Enum value)
        {
            Type enumType = value.GetType();
            EnumAttribute enuum = GetTableColumnAttribute<T>(System.Enum.GetName(enumType, value));
            return enuum.Describe;
        }
        #endregion

        #region 得到枚举类型的值以及名称
        /// <summary>
        /// 得到枚举类型的值以及名称
        /// </summary>
        /// <typeparam name="TEnum"></typeparam>
        /// <returns></returns>
        public static Dictionary<int, string> ToDescriptionDictionary<TEnum>()
        {
            Array values = System.Enum.GetValues(typeof(TEnum));
            Dictionary<int, string> nums = new Dictionary<int, string>();
            foreach (System.Enum value in values)
            {
                nums.Add(Convert.ToInt32(value), value.GetDescription<TEnum>());
            }
            return nums;
        }
        #endregion

        #region 根据注释得到对应的枚举类型（描述不能重复）
        /// <summary>
        /// 根据注释得到对应的枚举类型（描述不能重复）
        /// </summary>
        /// <typeparam name="TEnum">枚举类型</typeparam>
        /// <param name="describe">描述</param>
        /// <returns></returns>
        public static TEnum GetEnumByDescribe<TEnum>(this string describe) where TEnum : class
        {
            Array values = System.Enum.GetValues(typeof(TEnum));
            foreach (System.Enum value in values)
            {
                if (value.GetDescription<TEnum>() == describe)
                {
                    return value as TEnum;
                }
            }
            return default(TEnum);
        } 
        #endregion

    }
}
